package czx.wt.web.security;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.web.DefaultRedirectStrategy;
import org.springframework.security.web.RedirectStrategy;
import org.springframework.security.web.savedrequest.HttpSessionRequestCache;
import org.springframework.security.web.savedrequest.RequestCache;
import org.springframework.security.web.savedrequest.SavedRequest;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @Description: 类作用描述
 * @Author: ChenZhiXiang
 * @CreateDate: 2018/12/20 0020 17:58
 * @Version: 1.0
 */
@RestController
public class MySecurityController {

    @Value("${loginHtml}")
    private String loginHtml;
    @Value("${unAuth}")
    private String unAuthHtml;

    private static final Logger logger = LoggerFactory.getLogger(MySecurityController.class);

    /**
     * 用于请求的缓存
     */
    private RequestCache requestCache = new HttpSessionRequestCache();

    /**
     * 重定向工具类
     */
    private RedirectStrategy strategy = new DefaultRedirectStrategy();

    /**
     * 当需要身份认证跳转到这里
     * @param request
     * @param response
     * @return
     */
    @GetMapping("/auth/require")
    public String requireAuth(HttpServletRequest request, HttpServletResponse response) throws IOException {
        //拿到缓存的请求
        SavedRequest savedRequest = requestCache.getRequest(request,response);
        if (savedRequest != null){
            String url = savedRequest.getRedirectUrl();
            logger.info("引发跳转的地址"+url);
            if (StringUtils.endsWithIgnoreCase(url,".html") || url.contains("login")){
                //重定向到登录页
                strategy.sendRedirect(request,response,loginHtml);
            } else {
                //重定向到无权限页面
                strategy.sendRedirect(request,response,unAuthHtml);
            }
        }
        return null;
    }

}
